import tornado
import tornado.web
import method_stored

class BaseHandler(tornado.web.RequestHandler):
    # blog.csdn.net/moshowgame 解决跨域问题
    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Max-Age', 3600)
        self.set_header('Content-type', 'application/json')
        self.set_header('Access-Control-Allow-Methods', 'POST, GET,DELETE,PUT')
        # self.set_header('Access-Control-Allow-Methods', '*')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE')
        # self.set_header("Access-Control-Allow-Origin", origin_url)
        # self.set_header("Access-Control-Allow-Credentials", "true")
        # 如果header中有多种信息请一定要加种headers，如果header中存在user-token，必须在下面加入user-token，即self.set_header("Access-Control-Allow-Headers", "x-requested-with,token,user-token")
        # self.set_header("Access-Control-Allow-Headers", "x-requested-with,token")

    def options(self):
        self.set_status(200)
        self.finish()


#用户信息更新
class product_search(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            word =None
            page_id =0
            page_number =10

            
            if "word" in data.keys():
                word = data["word"]
            if "page_id" in data.keys():
                page_id = int(data["page_id"])
            if "page_number" in data.keys():
                page_number = int(data["page_number"])
            
            select_result = method_stored.get_product_list(word=word,page_id=page_id,page_number=page_number)
            if select_result!=None:
                for x in range(len(select_result)):
                    if type(select_result[x]) ==dict and "date" in select_result[x].keys() and select_result[x]["date"]!=None:
                        select_result[x]["date"] = select_result[x]["date"].strftime('%Y-%m-%d')
                        
            result["data"]["product_list"] = select_result
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)






#用户信息更新
class product_info(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}


        try:

            product_id = data["product_id"]
            
            # select_result = method_stored.course_by_id(product_id)
            table = "woniuhui_product"
            select_result = method_stored.info_product_table(product_id,table)
            if select_result!=None and select_result!="" and select_result!=None and select_result!=() and len(select_result)>0:
                if "date" in select_result[0].keys():
                    select_result[0]["date"] = select_result[0]["date"].strftime('%Y-%m-%d')
                if "body_image" in select_result[0].keys():
                    n=[]
                    if "," in select_result[0]["body_image"]:
                        n = select_result[0]["body_image"].split(",")
                    else:
                        n = [select_result[0]["body_image"]]
                    select_result[0]["body_image"] = n
                    
                result["data"]["course"] = select_result[0]
                msg="成功"
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                msg="获取课程失败"
                result["msg"] = msg

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass
        print(result)
        self.write(result)

application = tornado.web.Application([
    (r"/api/woniuhui/product_search", product_search),
    (r"/api/woniuhui/product_info", product_info)
])


# 问题
if __name__ == '__main__':
    # threading.Thread(target=get_pid.main2,).start()
    # 将socket对象添加到select或epoll中
    application.listen(8113)
    # 3. 将select或epoll开始死循环 While True:
    tornado.ioloop.IOLoop.instance().start()







